import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken, get, remove } from '@/utils/auth'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: 15000 // request timeout
})
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      config.headers['mbl_token'] = 'mbl ' + getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 501) {
      MessageBox.alert('系统未登录，请重新登录', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      })
      return Promise.reject('error')
    } else if (res.code !== 200) {
      MessageBox.alert(res.msg, '警告', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject('error')
    } else {
      return response
    }
  }, error => {
    Message({
      message: '登录连接超时（后台不能连接，请联系系统管理员）',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service

export function condition(arrs) {
  if (arrs instanceof Array) {
    const conditionList = []
    conditionList.push({
      col: arrs[0],
      rule: arrs[1],
      val: arrs[2]
    })
    return encodeURI(JSON.stringify(conditionList))
  } else {
    return encodeURI(JSON.stringify([{
      col: arrs[0],
      rule: arrs[1],
      val: arrs[2]
    }]))
  }
}

export function initBaseApi(modularUrl, modelUrl) {
  return {
    list(data) { return service({ url: `/${modularUrl}/${modelUrl}/list`, method: 'post', params: data }) },
    add(data) { return service({ url: `/${modularUrl}/${modelUrl}/add`, method: 'post', data }) },
    edit(data) { return service({ url: `/${modularUrl}/${modelUrl}/edit`, method: 'post', data }) },
    remove(id) { return service({ url: `/${modularUrl}/${modelUrl}/remove`, method: 'post', params: { id }}) },
    editStatus(data) { return service({ url: `/${modularUrl}/${modelUrl}/editStatus`, method: 'post', params: { data }}) },
    view(id) { return service({ url: `/${modularUrl}/${modelUrl}/view`, method: 'post', params: { id }}) },
    getAttributes() { return service({ url: `/${modularUrl}/${modelUrl}/getAttributes`, method: 'post' }) }
  }
}

